<template>
  <Spin :spinning="spinning">
    <a-card :class="$style.yc">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="basic" tab="分数查询">
          <BasicTable @register="registerTable" class="!p-0">
            <template #toolbar>
              <Upload
                name="file"
                accept=".xlsx,.xls"
                @change="handleImport"
                :before-upload="beforeUpload"
                @success="handleSuccess"
                :action="action"
                :headers="{ token: userStore.getToken }"
              >
                <a-button
                  type="primary"
                  v-if="route.meta?.buttonList?.includes('newQueryScoreSonButton')"
                >
                  上传查分文件
                </a-button>
              </Upload>
            </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'carbon:task-view',
                    label: '查看详情',
                    type: 'link',
                    onClick: handleView.bind(null, record),
                  },
                ]"
              />
            </template>
          </BasicTable>
        </a-tab-pane>
        <a-tab-pane key="record" tab="导入记录">
          <ImportRecord />
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </Spin>
</template>

<script lang="ts" setup name="newQueryScore">
import { BasicTable, useTable, TableAction } from '/@/components/Table'
import { columns, formSchemas } from './data'
import { list, exportFail } from '/@/api/queryScore'
import { useUserStore } from '/@/store/modules/user'
import { UploadProps, Upload, Spin } from 'ant-design-vue'
import { useMessage } from '/@/hooks/web/useMessage'
import { ref } from 'vue'
import { useGlobSetting } from '/@/hooks/setting'
import ImportRecord from './ImportRecord.vue'
import { downloadByUrl } from '/@/utils/file/download'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()

const route = useRoute()

const userStore = useUserStore()

const { createConfirm, createMessage } = useMessage()

const { apiUrl } = useGlobSetting()

const activeKey = ref<string>('basic')

//loading加载
const spinning = ref<boolean>(false)

const action = ref(`${apiUrl}/fscx/importData4Fscx`)

const [registerTable, { reload }] = useTable({
  rowKey: 'autoId',
  columns: columns(),
  showIndexColumn: false,
  api: list,
  formConfig: {
    labelWidth: 80,
    schemas: formSchemas(),
    autoSubmitOnEnter: true,
    colon: true,
  },
  searchInfo: {},
  useSearchForm: true,
  bordered: true,
  actionColumn: {
    title: '操作',
    width: 150,
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: 'right',
  },
})

function handleImport({ file }) {
  if (file.status === 'done') {
    spinning.value = false
    const { data, message, code } = file?.response
    if (code !== 200) {
      createMessage.error(`导入失败!${message}`)
      return
    }

    const { sbts, cgts, wjmc, importAutoId } = data

    if (sbts === 0) {
      createMessage.success(`导入成功,成功条数：${cgts}条`)
      reload()
    } else {
      reload()
      createConfirm({
        iconType: 'error',
        content: `<p>存在导入失败数据, 是否下载失败文件？</p><p><span class="text-green-500">成功条数：${cgts}</span>; <span class="text-red-500">失败条数：${sbts}</span>。</p>`,
        okText: '下载导入失败数据',
        onOk: async function () {
          exportFail({ importAutoId }).then(res => {
            const url = window.URL.createObjectURL(res)

            downloadByUrl({
              url,
              fileName: wjmc,
            })
          })
        },
      })
    }
  }
}

const beforeUpload: UploadProps['beforeUpload'] = file => {
  const { name } = file
  const fileName = name?.split('.') || ['']
  const isExcel = ['xls', 'xlsx', 'csv'].includes(fileName[fileName.length - 1])
  if (!isExcel) {
    createMessage.error('只能上传Excel表格')
  } else {
    spinning.value = true
  }

  return isExcel || Upload.LIST_IGNORE
}

function handleSuccess() {
  reload()
  spinning.value = false
}

function handleView(record) {
  router.push({
    name: 'FractionDetaile',
    query: {
      queryType: 'queryScore',
      autoId: record.autoId,
      kmdm: record.kmdm,
      kmpyzt: 'FORMAL',
      xsXm: record.xm,
      kdkskmId: record.ksbh,
      successAutoId: record.successAutoId,
    },
  })
}
</script>
<style lang="less" module>
.yc {
  :global {
    background-color: #fff;

    .ant-upload-list {
      display: none;
    }

    .ant-form {
      @apply px-6px;
    }
    .ant-card-body {
      padding: 0 16px 16px 16px;
    }
  }
}
</style>
